package com.sia.springcloud.filter;

import com.sia.springcloud.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import com.sia.springcloud.redis.RedisUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: Sirius
 * @Date: 2022/3/4 19:51
 * @Description: 鉴权过滤器，用来验证token
 **/
@Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Resource
    private RedisUtils redisUtils;

    private static final String AUTHORIZE_TOKEN = "token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();

        //2. 则获取响应
        ServerHttpResponse response = exchange.getResponse();

        //3. 如果是登录请求则放行
        if (request.getURI().getPath().contains("/registerController/login")) {
            //if (request.getURI().getPath().contains("/collectController")) {
            //经过测试，只要是请求路由中包含该指定路径会直接放行
            return chain.filter(exchange);
        }

        //3. 如果是注册请求则放行
        if (request.getURI().getPath().contains("/registerController/register")) {
            return chain.filter(exchange);
        }

        //3. 为了方便测试，暂时这么处理
        if (request.getURI().getPath().contains("/userController")) {
            return chain.filter(exchange);
        }

        // 2022.5.5
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        System.out.println("1---------------");
        List<String> stringList = queryParams.get("token");
        System.out.println("2---------------");

        if (null == stringList || stringList.isEmpty()) {
            System.out.println("缓存中没有该用户，表明该用户没有登录！");
        } else {
            String token = stringList.get(0);
            System.out.println("携带的token为:" + token);
            if (StringUtils.isNotEmpty(token)) {
                Claims claims = JwtUtils.parseJWT(token);
                String username = claims.getSubject();
                if (redisUtils.hasKey(username)) {
                    System.out.println("缓存中有该用户，表明该用户已经登录！");
                }
            }
        }


        // 将token放在了parameter中

        ////4. 获取请求头
        //HttpHeaders headers = request.getHeaders();
        ////5. 请求头中获取令牌
        //String token = headers.getFirst(AUTHORIZE_TOKEN);
        //
        ////6. 判断请求头中是否有令牌
        //if (StringUtils.isEmpty(token)) {
        //    //7. 响应中放入返回的状态吗, 没有权限访问
        //    response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //    //8. 返回
        //    return response.setComplete();
        //}
        //
        ////9. 如果请求头中有令牌则解析令牌
        //try {
        //    Claims claims = JwtUtils.parseJWT(token);
        //    String username = claims.getSubject();
        //
        //    //10. 判断缓存中是否有该用户
        //    if (!redisUtils.hasKey(username)) {
        //        //11. 返回
        //        return response.setComplete();
        //
        //    }
        //    //12. 判断缓存中用户名对应的token与返回的token是否一致
        //    if(!token.equals(redisUtils.get(username))){
        //        //13. 如果不一致返回
        //        return response.setComplete();
        //    }
        //} catch (Exception e) {
        //    log.warn(e.getMessage());
        //    //14. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
        //    response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //    //15. 返回
        //    return response.setComplete();
        //}
        //16. 放行
        return chain.filter(exchange);
    }


    /**
     * 给过滤器设置优先级，数值越低，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
